<?php
// +----------------------------------------------------------------------
// | 多客怪兽框架多平台开发框架 [ 以下开发工具自动生成-版权勿删 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2021~2024 http://www.dkyx.cc All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 刘泓宾（514660094@qq.com）
// +----------------------------------------------------------------------

namespace addons\cloud_market\model;

use think\model\concern\SoftDelete;

/**
 * 应用管理模型文件
 * Create by :  刘泓宾<514660094@qq.com>
 * Copyright :  copyright (c) 多客怪兽, www.dkyx.cc
 */
class CloudMarketAddon extends CloudMarketBaseModel
{
    // 配置软删除、启用回收站
    use SoftDelete;

    protected $deleteTime = "delete_time";

    // 字段自动类型转换
    protected $type = array(
        'token_prices' => 'json',
        'pic_images'   => 'json',
        'label_ids'    => 'json',
    );
    // 数据输出需要追加的属性
    protected $append = array(
        'label_names',
        'new_version'
    );

    public function __construct(array $data = [])
    {
        parent::__construct($data);
    }


    /**
     * 数据新增前执行
     * Create by :  刘泓宾<514660094@qq.com>
     * @param \think\Model $model
     * @return void
     */
    public static function onBeforeInsert(\think\Model $model)
    {
        parent::onBeforeInsert($model);
        // 权重自增
        $model->weigh = self::order('weigh', "desc")->value('weigh') + 1;
    }

    /**
     * 关联CloudMarketDeveloper模型
     * Create by :  刘泓宾<514660094@qq.com>
     * @return \think\model\relation\BelongsTo
     */
    public function developer()
    {
        return $this->belongsTo(CloudMarketDeveloper::class, 'dev_id', 'id')->field(['kefu', 'name', 'status', 'user_id', 'id', 'logo']);
    }

    /**
     * 关联CloudMarketUser模型
     * Create by :  刘泓宾<514660094@qq.com>
     * @return \think\model\relation\BelongsTo
     */
    public function user()
    {
        return $this->belongsTo(CloudMarketUser::class, 'user_id', 'id');
    }

    /**
     * 生成远程下拉多选数据
     * Create by :  刘泓宾<514660094@qq.com>
     * @param $val
     * @param $data
     * @return array
     */
    public function getLabelNamesAttr($val, $data)
    {
        if (!isset($data['label_ids'])) {
            return [];
        }
        $tags = [];
        // 二次修改，兼容旧数据
        if ($data['label_ids'] && !json_decode($data['label_ids'], true)) {
            if (!empty($data['label_ids'])) {
                $labels = CloudMarketLabel::where('id', 'in', $data['label_ids'])->visible(['name', 'id'])->select();
                $ids = [];
                foreach ($labels as $key => $value) {
                    $tags[] = $value['name'];
                    $ids[] = $value['id'];
                }
                $addon = (new CloudMarketAddon())->where(['id' => $data['id']])->find();
                $addon->label_ids = $ids;
                $addon->save();
                return $tags;
            }
        }
        $res = CloudMarketLabel::whereIn('id', json_decode($data['label_ids'], true))->select();
        foreach ($res as $key => $value) {
            $tags[] = $value['name'];
        }
        return $tags;
    }
    /***************************************************自定义的获取器***********************************/

    public function getAddonDataCountAttr($val,$data)
    {
        $data = array(
            'min_app_count' => (new CloudMarketAddonMinapp())->where(['aid' => $data['id']])->count(),
            'sku_count' => (new CloudMarketAddonSku())->where(['aid'=>$data['id']])->count(),
            'versions_count' => (new CloudMarketAddonVersions())->where(['aid' => $data['id']])->count(),
        );
        return $data;
    }


    /**
     * SKU信息
     * @return \think\model\relation\HasMany
     */
    public function skus()
    {
        return $this->hasMany(CloudMarketAddonSku::class, 'aid');
    }

    /**
     * 检查应用是否购买、授权、是否过期
     * Create by :  刘泓宾<514660094@qq.com>
     * @param $site_id
     * @param $addon_name
     * @return array
     */
    public function checkAddon($site_id, $addon_name)
    {
        if (!$site_id) {
            return array('code' => -1, 'msg' => '参数错误，站点ID不存在');
        }
        if (!$addon_name) {
            return array('code' => -1, 'msg' => "参数错误，应用名称不存在");
        }
        $addon = $this->where(['name' => $addon_name])->field('id,name,status,price,icon_image,type,down_count,detail_content,install_content')->find();
        if (!$addon) {
            return array('code' => -1, 'msg' => '当前应用不存在');
        }
        if ($addon['status'] == -1) {
            return array('code' => -1, 'msg' => '当前应用已被封禁');
        }
        //检查是否购买此应用
        $site_addon = (new CloudMarketSiteAddon())->where(['site_id' => $site_id, 'addon_id' => $addon['id']])->find();
        if (!$site_addon) {
            return array('code' => -1, 'msg' => '当前站点未购买或授权此应用');
        }
        if ($site_addon['status'] == -1) {
            return array('code' => -1, 'msg' => '当前站点禁止安装此应用');
        }
        if ($site_addon['servicetime'] < time()) {
            return array('code' => -1, 'msg' => "当前站点服务已过期，请到应用市场续费服务时间");
        }
        $addon['site_addon'] = $site_addon;
        return array('code' => 0, 'msg' => 'ok', 'data' => $addon);
    }


    public function getSkuPriceAttr($value, $data)
    {
        // 获取价格区间,得到最低和最高价格
        $sku = CloudMarketAddonSku::where(['aid' => $data['id']])->order('price', 'asc')->select();
        if (!$sku) {
            return $data['price'];
        }
        $prices = [];
        foreach ($sku as $k => $v) {
            $prices[] = $v['price'];
        }
        if (count($prices) === 1) {
            return $prices[0];
        } else if (count($prices) > 1) {
//            return min($prices) . '-' . max($prices);
            return $prices[0] . '-' . $prices[count($prices) - 1];
        } else {
            return $data['price'] ?? '';
        }
    }

    // public function getLabelsAttr($value, $data)
    // {
    //     if (!empty($data['label_ids'])) {
    //         return CloudMarketLabel::where('id', 'in', $data['label_ids'])->visible(['name', 'id'])->select();
    //     } else {
    //         return [];
    //     }
    // }


    public function getTokenCountAttr($value, $data)
    {
        $token_count = CloudMarketSiteAddonToken::where(["aid" => $data['id']])->count();
        return $token_count;
    }

    public function getBuyCountAttr($value, $data)
    {
        $order_count = CloudMarketOrder::where(["aid" => $data['id'], "status" => 1])->count();
        return $order_count;
    }

    public function getPackageCountAttr($value, $data)
    {
        $package_count = CloudMarketAddonSku::where(['aid' => $data['id']])->count();
        return $package_count;
    }

    public function getVersionDateAttr($value, $data)
    {
        $createtime = CloudMarketAddonVersions::where(['aid' => $data['id']])->order('id', 'desc')->value('createtime');
        if (!$createtime) {
            $createtime = $data['createtime'] ?? time();
        }
        return date("Y-m-d", $createtime);
    }

    //获取最新版本
    public function getNewVersionAttr($value, $data)
    {
        $ver = CloudMarketAddonVersions::where(['aid' => $data['id'], 'show_switch' => 1])->order('id', 'desc')->value('version');
        return $ver ?: '1.0';
    }

    public function getVersionListAttr($value, $data)
    {
        $list = CloudMarketAddonVersions::where(['aid' => $data['id'], 'show_switch' => 1])->order('id', 'desc')->limit(0, 10)->select();
        return $list;
    }

    //设置图标地址
    public function setIconImageAttr($value)
    {
        return cdnurl($value);
    }

    //获取SKU信息
    public function getAddonMsgForOrderBySku($aid, $sku_id = 0)
    {
        $addon = $this->find($aid);
        $res = array(
            'title' => $addon['title'],
            'price' => $addon['price']
        );
        if ($sku_id > 0) {
            $sku = (new CloudMarketAddonSku())->find($sku_id);
            $res['title'] = $addon['title'] . "-" . $sku['name'];
            $res['price'] = $sku['price'];
        }
        return $res;
    }

    // //获取用户
    // public function getUserAttr($value, $data)
    // {
    //     $res = CloudMarketUser::get($data['user_id'])->append();
    //     return $res;
    // }

    //获取图标地址
    public function getIconImageUrlAttr($value, $data)
    {
        if (!empty($data['icon_image'])) {
            return cdnurl($data['icon_image']);
        } else {
            return "";
        }
    }

    public function getPicImagesAttr($value, $data)
    {
        if(!isset($data['pic_images'])){
            return [];
        }
        // 老数据转换，以前的是用的,隔开的，现在是存的数组
        if (json_decode($data['pic_images'], true)) {
            $images = json_decode($data['pic_images'], true);
            foreach ($images as $key => $value) {
                if ($value) {
                    if (!preg_match('/^http(s)?:\/\//i', $images[$key])) {
                        // 添加前缀
                        $images[$key] = 'https://dkyx-1251560393.cos.ap-chengdu.myqcloud.com' . $images[$key];
                    }
                }
            }
            $this->pic_images = $images;
            $this->save();
            return $images;
        } else {
            $pic_images = explode(",", $data['pic_images']);
            // 存储数组
            $res = (new CloudMarketAddon())->find($data['id']);
            $images = [];
            foreach ($pic_images as $key => $value) {
                if ($value) {
                    $images[] = $value;
                }
            }
            if ($images) {
                $res->pic_images = $pic_images;
                $res->save();
                return $pic_images;
            }
            return [];
        }
    }

    //封面单图地址
    public function getPicImageUrlAttr($value, $data)
    {
        $images = $data['pic_images'];
        if (!empty($images)) {
            return cdnurl($images[0]);
        } else {
            return "";
        }
    }

    //获取图标地址
    public function getIconImageAttr($val)
    {
        // 如果值为空，直接返回
        if (empty($val)) {
            return $val;
        }
        // 检查是否已经包含 http 或 https 前缀
        if (!preg_match('/^http(s)?:\/\//i', $val)) {
            // 添加前缀
            $val = 'https://dkyx-1251560393.cos.ap-chengdu.myqcloud.com' . $val;
            $this->icon_image = $val;
            $this->save();
        }
        return $val ? cdnurl($val) : '';
    }

    // 获取文档地址

    public function getDocsAttr($val, $data)
    {
        $docs = (new CloudMarketDocs())->where(['addon_id' => $data['id']])->find();
        return $docs ? $docs->toArray() : [];
    }
}
